﻿using System;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace PackageEditor.Helper
{
    public partial class HexHelper : Form
    {
        private Stream stream;
        public HexHelper(Stream s)
        {
            InitializeComponent();
            this.stream = s;
        }

        private void HexHelper_Load(object sender, EventArgs e)
        {
            this.Icon = Properties.Resources.Icon;

            BinaryReader r = new BinaryReader(stream);
            byte[] Data = r.ReadBytes((int)stream.Length);

            StringBuilder sb = new StringBuilder(Data.Length * 2);
            sb.Append(" ".PadLeft(10));
            for (int i = 0; i < 16; i++) sb.AppendFormat("{0:X2} ", i);
            sb.AppendLine();
            int LineCount = Data.Length / 16;
            int remainder = Data.Length % 16;
            int count = 0;

            for (int i = 0; i < LineCount; i++)
            {
                sb.AppendFormat("{0:X8}: ", i * 16);
                for (int m = 0; m < 16; m++) sb.AppendFormat("{0:X2} ", Data[count++]);
                count -= 16;
                sb.Append("  ");
                for (int m = 0; m < 16; m++) sb.Append(ToChar(Data[count++]));
                sb.AppendLine();
            }

            sb.AppendFormat("{0:X8}: ", (LineCount + 1) * 16);
            for (int m = 0; m < remainder; m++) sb.AppendFormat("{0:X2} ", Data[count++]);
            count -= remainder;
            sb.Append(" ".PadLeft((16 - remainder) * 3 + 2));
            for (int m = 0; m < remainder; m++) sb.Append(ToChar(Data[count++]));

            txtValue.Text = sb.ToString();

        }

        private static char ToChar(byte b)
        {
            return b < 0x20 || b > 0x7e ? '.' : (char)b;
        }
    }
}
